/**
 * Created by Administrator on 2017/8/23 0023.
 */


//var route = /** @type {ol.geom.LineString} */ (new ol.format.Polyline({
//    factor: 1e6
//}).readGeometry(polyline, {
//    dataProjection: 'EPSG:4326',
//    featureProjection: 'EPSG:3857'
//}));
//
//var routeCoords = route.getCoordinates();
//var routeLength = routeCoords.length;



var LineStyles = {
    'route': new ol.style.Style({
        stroke: new ol.style.Stroke({
            width: 6, color: [237, 212, 0, 0.8]
        })
    }),
    'icon': new ol.style.Style({
        image: new ol.style.Icon({
            anchor: [0.5, 1],
            src: 'icon/flag_32px_end.ico'
        })
    }),
    'geoMarker': new ol.style.Style({
        image: new ol.style.Circle({
            radius: 7,
            snapToPixel: false,
            fill: new ol.style.Fill({color: 'black'}),
            stroke: new ol.style.Stroke({
                color: 'white', width: 2
            })
        })
    })
};
var animating = false;
var speed, now;
var speedInput ;
var startButton;
var geoMarker;
var startMarker;
var endMarker;
var center;
 var route ;
var routeCoords ;
var routeLength ;
var addLineLayer = false;
var lineLayer;

var source;
function addLineLayerFun(){

    if(addLineLayer){
        if(!!lineLayer){
            map.removeLayer(lineLayer);
            addLineLayer = !addLineLayer;
            return
        }
    }
    addLineLayer = !addLineLayer;
    if(!!lineLayer){
        map.addLayer(lineLayer);
        map.getView().setCenter(center);
        return
    }



    //读取GPS信息
    var pointArr = line;
    //当前gps数据无需进行修正
    if(false){
        for(var i= 0,size = pointArr.length;i<size;i++){
            pointArr[i] = [changeMapLon(pointArr[i][0]),changeMapLon(pointArr[i][1])];
        }
    }
    //将经纬度全部转换为坐标系
    if(true){
        for(var i= 0,size = pointArr.length;i<size;i++){
            pointArr[i] = ol.proj.fromLonLat([pointArr[i][0],pointArr[i][1]]);
        }
    }

    route =  new ol.geom.LineString(pointArr);
    routeCoords = pointArr;
    routeLength = routeCoords.length;
    center =pointArr[0];
    //center = ol.proj.fromLonLat([pointArr[0][0],pointArr[0][1]]);
    //console.log([pointArr[0][0],pointArr[0][1]]);
    //var endPint = ol.proj.fromLonLat([pointArr[pointArr.length-1][0],pointArr[pointArr.length-1][1]]);
    endPint = pointArr[pointArr.length-1];
    geoMarker = new ol.Feature({
        type: 'geoMarker',
        geometry: new ol.geom.Point(center)
    });
     startMarker = new ol.Feature({
        type: 'icon',
        geometry: new ol.geom.Point(center)
    });
    endMarker = new ol.Feature({
        type: 'icon',
        geometry: new ol.geom.Point(endPint)
    });
    //将gps坐标数组转换为坐标
    //var linePolygon = turf.lineString(pointArr);
    //geojsonObject.features.push(linePolygon);
    //route = /** @type {ol.geom.LineString} */ (new ol.format.Polyline({
    //
    //})).readGeometry(linePolygon, {
    //    dataProjection: 'EPSG:4326',
    //    featureProjection: 'EPSG:3857'
    //});
    var routeFeature = new ol.Feature({
        type: 'route',
        geometry: route
    });



    map.getView().setCenter(center);
    //var lineFeature = (new ol.format.GeoJSON()).readFeatures(geojsonObject,{dataProjection:"EPSG:4326",featureProjection:"EPSG:3857"});
    //for (var i= 0,size = lineFeature.length;i<size;i++){
    //    lineFeature[i].type = 'route';
    //}
    var lineFeature =[];
    //lineFeature.push(routeFeature);
    lineFeature.push(geoMarker);
    lineFeature.push(startMarker);
    lineFeature.push(endMarker);
    source = new ol.source.Vector({
        features: lineFeature
    });

    lineLayer = new ol.layer.Vector({
        source: source,
        //style: LineStyles
        style: function(feature) {
            // hide geoMarker if animation is active
            if (animating && feature.get('type') === 'geoMarker') {
                return null;
            }
            return LineStyles[feature.get('type')];
        }

    });
    map.addLayer(lineLayer);


    //alert('add Line success');
    //startButton.addEventListener('click', startAnimation, false);
     speedInput = document.getElementById('speed');
    startButton = document.getElementById('start-animation');
    startButton.addEventListener('click', startAnimation, false);

}

var moveFeature = function(event) {
    var vectorContext = event.vectorContext;
    var frameState = event.frameState;

    if (animating) {
        var elapsedTime = frameState.time - now;
        // here the trick to increase speed is to jump some indexes
        // on lineString coordinates
        var index = Math.round(speed * elapsedTime / 1000);

        if (index >= routeLength) {
            stopAnimation(true);
            return;
        }

        var currentPoint = new ol.geom.Point(routeCoords[index]);
        var feature = new ol.Feature(currentPoint);
        feature.setStyle(LineStyles.geoMarker);
        //map.addFeature(feature);
        source.addFeature(feature);
        //vectorContext.drawFeature(feature, LineStyles.geoMarker);
    }
    // tell OpenLayers to continue the postcompose animation
    map.render();
};

function startAnimation() {
    if (animating) {
        stopAnimation(false);
    } else {
        animating = true;
        now = new Date().getTime();
        speed = speedInput.value;
        startButton.textContent = 'Cancel Animation';
        // hide geoMarker
        //geoMarker.setStyle(null);
        // just in case you pan somewhere else
        //map.getView().setCenter(center);
        map.on('postcompose', moveFeature);
        map.render();
    }
}


/**
 * @param {boolean} ended end of animation.
 */
function stopAnimation(ended) {
    animating = false;
    startButton.textContent = 'Start Animation';

    // if animation cancelled set the marker at the beginning
    var coord = ended ? routeCoords[routeLength - 1] : routeCoords[0];
    /** @type {ol.geom.Point} */ (geoMarker.getGeometry())
        .setCoordinates(coord);
    //remove listener
    map.un('postcompose', moveFeature);
}



